package com.efounder.fragment;

import java.io.File;
import java.util.Hashtable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.ospmobilelib.R;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.SnapShot;
import com.efounder.view.titlebar.AbTitleBar;
import com.efounder.widget.ESPWebView;
import com.pansoft.appcontext.AppConstant;
import com.pansoft.espcomp.DateWindows;
import com.pansoft.espcomp.DateWindows.DateOnclickListener;

public class SimpleWebFragmentNoRefresh_old extends Fragment {

	private static final String TAG = "SimpleWebFragment";
	private StubObject mMenuItem;
	private String titleStr;
//	CustomProgressDialog dialog;
	private View rootView;// 缓存Fragment view
	AbTitleBar title ;
	ESPWebView web ;
	Boolean isShowBottom;
	FrameLayout fl;
	String forms;
	 ESPWebView wv;
	 ImageView imageView;
	 RelativeLayout include;

	public SimpleWebFragmentNoRefresh_old(StubObject menuItem,String title) {
		this.mMenuItem = menuItem;
		this.titleStr = title;
		
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
	
		
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onResume() {
		super.onResume();
	/*	TabBottomActivity menuFrag = TabBottomActivity.getInstance();
        isShowBottom = (menuFrag.getBottomBar().getVisibility()==View.VISIBLE);
		if(isShowBottom)
		menuFrag.getBottomBar().setVisibility(View.GONE);*/
	}


	@Override
	public void onStop() {
		super.onPause();
	/*	if(isShowBottom){
			TabBottomActivity menuFrag = TabBottomActivity.getInstance();
			menuFrag.getBottomBar().setVisibility(View.VISIBLE);
			}*/
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.normalwebview, container, false);
		
		Hashtable menuTable = mMenuItem.getStubTable();
		String webUrl = (String) menuTable.get("url");
		String param = (String) menuTable.get("param");
		String value = (String) menuTable.get("value");
		String titleName = (String)menuTable.get("caption");
		forms = (String)menuTable.get("forms");
		String contentView =  (String)menuTable.get("contentView");
		registerBoradcastReceiver();
		
		include = (RelativeLayout) rootView.findViewById(R.id.include);
		TextView title = (TextView)rootView.findViewById(R.id.fragmenttitle);
		title.setText(titleName);
		LinearLayout leftbacklayout = (LinearLayout) rootView.findViewById(R.id.leftbacklayout);
		leftbacklayout.setVisibility(View.VISIBLE);
	

		leftbacklayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 SimpleWebFragmentNoRefresh_old.this.getFragmentManager().popBackStack();
			}
		});
		
		
		Button buttonRight = (Button) rootView.findViewById(R.id.closeButton);
		buttonRight.setVisibility(View.VISIBLE);
		buttonRight.setBackgroundResource(R.drawable.rightmenu);
		buttonRight.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//web.loadUrl("www.baidu.com");
				//new MonthWindows(SimpleWebFragment.this.getActivity(), v);
			final DateWindows dateWindows = 	new DateWindows(SimpleWebFragmentNoRefresh_old.this.getActivity(), v);
			dateWindows.setDateOnclickListener(new DateOnclickListener() {
				
				@Override
				public void ondateCalendarClick(String date) {
					// TODO Auto-generated method stub
					dateWindows.dismiss();
					//web.loadUrl("http://www.baidu.com");
				}
			});
			}
		});
		
		
		/*StringBuffer strUrl = null;
//		webUrl = "http://www.baidu.com";
		if (param != null&&false) {
			SharedPreferences share = getActivity().getSharedPreferences(
					BaseApp.UserInfo, Context.MODE_PRIVATE);
//			SharedPreferences sharedPreferences = getActivity().getSharedPreferences(ESPApplication.UserInfo,
//					//LoginSettingsActivity.SETTING_FILE,
//							Context.MODE_PRIVATE);

			String[] paramArr = param.split(";");
			String[] valueArr = value.split(";");

			String values = null;
			// 拼接url
			strUrl = new StringBuffer().append(webUrl + "?");
				
			for (int i = 0; i < paramArr.length; i++) {

				//拼接& 第一个参数没有&符号
				if(i >= 1){
					strUrl = strUrl.append("&");
				}
				// 拼接key
				strUrl = strUrl.append(paramArr[i]);
				// 拼接=
				strUrl = strUrl.append("=");

				// 拼接value
				values = valueArr[i];
				if (values.equals("@USERNAME@")) {
					values = share.getString(BaseApp.UserInfo_ID, "");

				} else if (values.equals("@PASSWORD@")) {
					values = share.getString(BaseApp.UserInfo_PWD, "");

				} else if (values.equals("@AD@")) {
					values = share.getString("dataFlag", "");

				} else if (values.equals("@EMAIL@")) {
					values = share.getString(BaseApp.UserInfo_EMAIL, "");
				} else if (values.equals("@PHONENUMBER@")) {
					values = share.getString(BaseApp.UserInfo_PHONENUMBER, "");
				}
				strUrl = strUrl.append(values);	
			}
			webUrl = strUrl.toString();
		}*/
		//web = (ESPWebView) rootView.findViewById(R.id.mywebview);
		
		/* FrameLayout fl = MyStaticWebView.getFl();
		 FrameLayout fl = new FrameLayout(this.getActivity());
		 LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		 fl.setLayoutParams(params);
		  if(fl.getParent()!=null)
			     ((ViewGroup)fl.getParent()).removeAllViews();
				 
	     ImageView imageView = MyStaticWebView.getKuaiZhao();*/
		 fl =  new FrameLayout(this.getActivity());
		 LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		 fl.setLayoutParams(params);
		if (null != forms) {
			LoadingDataUtilBlack.show(SimpleWebFragmentNoRefresh_old.this.getActivity(),"初始化界面");

			imageView = new ImageView(this.getActivity());

			/*
			 * if(imageView.getParent()!=null)
			 * ((ViewGroup)imageView.getParent()).removeAllViews();
			 */

			Bitmap bm = null;
			String menuIcon = AppConstant.APP_ROOT + "/kuaizhao/" + forms
					+ ".png";
			System.out.println("xxxxxx" + menuIcon);
			File file = new File(menuIcon);
			if (file.exists()) {
				bm = BitmapFactory.decodeFile(menuIcon);
				// bitmapList.add(bm);
			} else {
				bm = BitmapFactory.decodeResource(this.getActivity()
						.getResources(), R.drawable.ic_launcher);
			}

			imageView.setImageBitmap(bm);
			// setting image position
			imageView.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

			fl.addView(imageView);
		}else{
			include.setVisibility(View.VISIBLE);
			com.pansoft.espcomp.ESPWebView wv = (com.pansoft.espcomp.ESPWebView) rootView.findViewById(R.id.mywebview);
			wv.setWebChromeClient(new WebChromeClient());
			wv.setWebViewClient(new WebViewClient() {  
		            public boolean shouldOverrideUrlLoading(WebView view, String url)  
		            {   
		                //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边  
		                view.loadUrl(url);  
		                        return true;  
		            }         
		             }); 
			 LayoutParams params1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			 wv.setLayoutParams(params1);
			 wv.loadUrl(webUrl);
			// fl.addView(wv);
			 return rootView;
			
		}
	     
	    		
	    		
		 
		
		  //fl.addView(wv);
		  
		  return fl;
		  
		// 
		
		/*System.out.println(String.valueOf(webUrl));
		web.loadUrl(String.valueOf(webUrl));*/
		//return rootView;
	}

	/*private class webClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
		//	dialog.show();
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			LoadingDataUtilBlack.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			LoadingDataUtilBlack.show();
		}
		
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			handler.proceed();// 接受证书
			LoadingDataUtilBlack.dismiss();
		}

	}*/
	@Override
	public void onStart() {
	/*	title = ((TabBottomActivity)getActivity()).getTitleBar();
		title.setTitleText(titleStr);
		title.setVisibility(View.GONE);*/
		super.onStart();
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 //BroadCastutil.getinstance().unregisterWebBroadcastList((Context)SimpleWebFragmentNoRefresh.this.getActivity());
	}
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if(action.equals(forms)){  
            	String type = intent.getStringExtra("type");
            	if(("hideKZ").equals(type)){
            		
            		imageView.setVisibility(View.VISIBLE);
            		//wv.setVisibility(visibility)
            		
            		return;
            	}
            	
            	 wv = MyStaticWebView.getWv();
    			 wv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
    			         LayoutParams.FILL_PARENT));
    			 if(wv.getParent()!=null)
    			     ((ViewGroup)wv.getParent()).removeView(wv);
    			// fl.removeAllViews();
    			 imageView.setVisibility(View.GONE);
    			 //wv.setVisibility(View.VISIBLE);
    			 fl.addView(wv);
    			 //fl.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    			 wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    				   @SuppressLint("NewApi") @Override
    				   public void onGlobalLayout() {
    					   Handler handler = new Handler();
    						handler.postDelayed(new Runnable() {
    							
    							@Override
    							public void run() {

    								  SnapShot ss = new SnapShot();
    			    	    			 String fromtilte = forms+".png";
    			    	    			 String  dir = AppConstant.APP_ROOT+"/kuaizhao";
    			    	    			 
    			    	    			 
    			    	    			 ss.shot(wv, dir, fromtilte);
    							}
    						}, 1000*2);

    				   
    	    			  if (Build.VERSION.SDK_INT<16) {
    	                        fl.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    	                    } else { 
    	                        fl.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    	                    }
    				   }
    				});
            	// SimpleWebFragmentNoRefresh.this.getActivity().unregisterReceiver(mBroadcastReceiver); 
            }
    			 
        }  
          
    };  
    public void registerBoradcastReceiver(){  
    	boolean a  = (null!=forms);
    	System.out.println(a);
    	if(!a)return;
    	boolean b  = (!("").equals(forms));
    	System.out.println(b);
    	if(null!=forms||!("").equals(forms)){
        IntentFilter myIntentFilter = new IntentFilter();  
        myIntentFilter.addAction(forms);  
        //注册广播        
       this.getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);  
       BroadCastutil.getinstance().addbroadCast(mBroadcastReceiver);
    	}
    }  
    
	
}
